import { Square } from "./Square";
import { IPoint, TShape } from "./types";

export class SquareGroup {
  private _squares: readonly Square[];
  public get squares() {
    return this._squares;
  }

  public get centerPoint() {
    return this._centerPoint;
  }
  public get shape() {
    return this._shape;
  }
  public set centerPoint(v: IPoint) {
    this._centerPoint = v;
  }
  centerPointMove(p: IPoint) {
    this._centerPoint = p;
    this.setSquarePoints();
  }

  private setSquarePoints() {
    this._shape.forEach((p, i) => {
      this.squares[i].changePoint({
        x: this.centerPoint.x + p.x,
        y: this.centerPoint.y + p.y,
      });
    });
  }

  constructor(
    public _shape: TShape,
    private _centerPoint: IPoint,
    private _color: string
  ) {
    // 设置小方块的数组
    this._squares = this._shape.map((p) => {
      const x = p.x + this._centerPoint.x;
      const y = p.y + this._centerPoint.y;
      return new Square({ x, y }, this._color);
    });
  }

  /** 旋转方向, 是否顺时针 */
  isClock = true;
  // 得到旋转后的形状
  afterRotateShape(): TShape {
    if (this.isClock) {
      // 顺时针旋转
      return this._shape.map((p) => {
        return {
          x: -p.y,
          y: p.x,
        };
      });
    } else {
      // 逆时针旋转
      return this._shape.map((p) => {
        return {
          x: p.y,
          y: -p.x,
        };
      });
    }
  }
  rotate() {
    const newShape = this.afterRotateShape();
    this._shape = newShape;
    this.setSquarePoints();
  }
}
